<?php
/**
 * Description:
 * Author: hezhizheng
 * Date: 2018/11/15
 * Time: 9:57
 * Created by Created by Panxsoft.
 */

namespace App\Services\Customers\Register;

use App\Models\Customers\Customer;
use App\Models\Customers\CustomerGroup;
use App\Models\Language;
use App\Models\Store;
use App\Services\Common\VerifyCodeService;
use App\Services\EasySms\EasySmsService;
use App\Services\MobileApp\AppEnv;
use App\Services\Utils\Transaction;

class TelephoneRegisterService
{
    private $customer;

    public function __construct()
    {
        $this->customer = new Customer;
    }

    /**
     * @param Customer $customer
     * @return Customer|\Illuminate\Database\Eloquent\Model
     * @throws \Exception
     */
    public function register(Customer $customer)
    {
        // 验证 手机验证码
        $service = new VerifyCodeService;

        $cache_key = $service->getRegisterCacheKey($customer->telephone, $customer->dial_code);
        if (config('pkx.debug.customer.verify_tel_register_code')) {
            $service->checkVerifyCode($cache_key, $customer->verify_code);
        }

        $data = $this->assembleData($customer);

        $reg = Transaction::handle(function() use($data){
            $reg = $this->customer->create($data);
            (new EmailRegisterService)->relateSocialiteAccount($reg->customer_id);

            return $reg;
        });

        // 销毁验证过后验证码
        $service->destroyUsedVerifyCode($cache_key);

        // 获取登录的jwt_token
        (new EmailRegisterService)->generateJwtToken($reg);

        return $reg;
    }

    /**
     * @param Customer $customer
     * @return array
     */
    private function assembleData(Customer $customer)
    {
        $data = [
            'telephone'         => $customer->telephone,
            'dial_code'         => $customer->dial_code,
            'password'          => bcrypt($customer->password),
            'language_id'       => AppEnv::languageId(),
            'customer_group_id' => AppEnv::customerGroupId(),
            'store_id'          => Appenv::storeId(),
            'date_added'        => (string)now(),
            'ip'                => $customer->ip,
            'status'            => Customer::STATUS_ENABLE,
            'fullname'          => $customer->fullname,
            'image'             => $customer::avatarDefault(),
        ];

        return $data;
    }
}